package com.hiwan.system.web.auth;

import java.sql.Date;
import java.util.List;

import org.framework.session.SessionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hiwan.platform.util.DateUtil;
import com.hiwan.platform.util.StackTraceUtil;
import com.hiwan.system.pojo.AuthInfo;
import com.hiwan.system.pojo.RoleInfo;
import com.hiwan.system.pojo.UserRelation;
import com.hiwan.system.service.auth.AuthInfoService;
import com.hiwan.system.service.user.UserService;

@Controller
@RequestMapping("/auth")
public class AuthController{
	
	@Autowired
	private AuthInfoService authInfoService;
	@Autowired
	private UserService userService;
	
	protected Logger logger = LoggerFactory.getLogger(getClass());

	@RequestMapping("toAuth.do")
	public String toAuth() {
		return "auth/auth";
	}
	
	
	/**
	 * 根据条件查询转授权信息列表
	 * @return
	 */
	@RequestMapping("list.do")
	public String list(AuthInfo authInfo,ModelMap model){
		if(authInfo==null){
			authInfo = new AuthInfo();
		}
		authInfo.setAuthUser(SessionContext.getUserId());
		List<AuthInfo> authInfoList = authInfoService.selectAuthInfoList(authInfo);
		model.put("authInfoList", authInfoList);
		return "auth/authInfoList";
	}
	
	
	/**
	 * 查询转授权详细信息
	 * @return
	 */
	@RequestMapping("detail.do")
    public String detail(ModelMap model,AuthInfo authInfo){
		
    	authInfo = authInfoService.selectAuthInfoById(authInfo.getAuthUser(),authInfo.getSeqNo());
    	if(!authInfo.getAuthUser().equals(SessionContext.getUserId())){
    		model.put("isAdministrator", "1");//是否是系统管理员0--否，1--是
    	}
    	List<RoleInfo> roleList = authInfoService.selectRoleListById(authInfo.getAuthUser());
    	List<RoleInfo> choosedRoleList = authInfoService.setChoosedRoleId(authInfo);
    	
    	model.put("sendFlag", "2");
    	model.put("authInfo", authInfo);
    	model.put("roleList", roleList);
    	model.put("choosedRoleList", choosedRoleList);
    	return "auth/authInfoDetail";
    }
	
	 /**
     * 新增转授权信息
     * @return
     */
	@RequestMapping("addAuth.do")
    public String addAuth(ModelMap model,AuthInfo authInfo ){
		List<RoleInfo> roleList;
    	if(authInfo==null){
    		authInfo = new AuthInfo();
    	}
    	//如果是系统管理员发起，授权人和授权机构为空，弹出框选择
    	//否则默认是当前登录人和登录机构
    	if(!SessionContext.getUserRole().contains("01")){
    		authInfo.setAuthOrg(SessionContext.getOrgId());
        	authInfo.setAuthUser(SessionContext.getUserId());
        	authInfo.setAuthStatus("1");//有效状态
        	
        	model.put("isAdministrator", "0");//是否是系统管理员0--否，1--是
        	roleList = authInfoService.selectRoleListById(SessionContext.getUserId());
        	//List<RoleInfo> choosedRoleList = new ArrayList<RoleInfo>();
    	}else{
    		//系统管理员
    		model.put("isAdministrator", "1");//是否是系统管理员0--否，1--是
    		authInfo.setAuthStatus("0");//待确认状态
    		roleList = authInfoService.selectRoleListById(SessionContext.getUserId());
    		String verifyCode = authInfoService.getRandomNoRepeat();
    		authInfo.setVerifyCode(verifyCode);
        	//choosedRoleList = new ArrayList<RoleInfo>();
    	}
    	authInfo.setUpdateOrg(SessionContext.getOrgId());
    	authInfo.setUpdateUser(SessionContext.getUserId());
    	authInfo.setAuthStartTime(DateUtil.getDateString(new Date(System.currentTimeMillis()),"yyyy-MM-dd"));
    	
		model.put("sendFlag", "1");
		model.put("roleList", roleList);    	
    	model.put("authInfo", authInfo);
    	
    	return "auth/authInfoDetail";
    }
	
	
	   /**
     * 获取授权用户的角色信息
     * @return
     */
	@RequestMapping("getRoleStrByUserId.do")
    public @ResponseBody String[] getRoleStrByUserId(String authUser){
    	Object[] ret = null;
    	List<UserRelation> urList = userService.selectUserRelations(authUser);
    	UserRelation ur = urList.get(0);
    	ret = authInfoService.setRoleName(ur.getRoleIdstr());
    	
    	String[] data =(String[]) ret;
    	
    	return data;
    }
	
	  
    /**
     * 保存转授权信息
     * @return
     */
	@RequestMapping("save.do")
    public @ResponseBody String[] save(AuthInfo authInfo,String isAdministrator){
    	String[] ret = null;
    	try {
    		ret = authInfoService.checkAuthInfo(authInfo,"1",isAdministrator);
			if("ok".equals(ret[0])){
				authInfoService.insertAuthInfo(authInfo,isAdministrator);
				ret = new String[]{"ok","保存成功！",String.valueOf(authInfo.getSeqNo())};
			}
		} catch (Exception e) {
			logger.error(StackTraceUtil.getStackTrace(e));
			ret = new String[]{"fail",e.getMessage()};
		}
    	return ret;
    }
	
	  /**
     * 修改转授权信息
     * @return
     */
	@RequestMapping("update.do")
    public @ResponseBody String[] update(AuthInfo authInfo,String isAdministrator){
    	String[] ret = null;
    	//判断是否需要发送短信通知
    	try {
			ret = authInfoService.checkAuthInfo(authInfo,"2",isAdministrator);
			if("ok".equals(ret[0])){
				authInfoService.updateAuthInfo(authInfo,isAdministrator);
				ret = new String[]{"ok","保存成功！",String.valueOf(authInfo.getSeqNo())};
			}
		} catch (Exception e) {
			logger.error(StackTraceUtil.getStackTrace(e));
			ret = new String[]{"fail",e.getMessage()};
		}
    	return ret;
    }
	
	   
    /**
     * 删除授权信息
     * @return
     */
	@RequestMapping("delete.do")
    public @ResponseBody String[] delete(AuthInfo authInfo){
    	String[] ret = null;
    	authInfoService.deleteAuthInfo(authInfo.getAuthUser(),authInfo.getSeqNo());
    	ret = new String[]{"ok","删除成功!"};
    	return ret;
    }
}
